package sf.view.fields;

import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;

import javax.swing.JLabel;
import javax.swing.JTextField;

import sf.model.fields.NumberFieldModel;
import sf.model.fields.AbstractFieldModel;
import sf.model.fields.event.FieldChangeEvent;

public class NumberField extends DecimalField
{

	private static final long serialVersionUID = 4012875536812503984L;

	private class NumberFieldController implements ActionListener,
			FocusListener
	{

		
		public void actionPerformed(ActionEvent e)
		{
			updateValue();
		}

		
		public void focusGained(FocusEvent e)
		{

		}

		
		public void focusLost(FocusEvent e)
		{
			updateValue();
		}

		private void updateValue()
		{
			if (((NumberFieldModel) getModel()).check(inputField.getText())
					&& !inputField.getText().equals(getModel().getValue()))
			{
				model.setValue(inputField.getText());
			}
		}

	}

	private JTextField inputField;
	private JLabel label;

	private NumberFieldModel model;
	private NumberFieldController controller;

	public NumberField()
	{
		model = new NumberFieldModel();
		controller = new NumberFieldController();
		label = new JLabel(getLabelText());
		add(label, BorderLayout.WEST);
		inputField = new JTextField();
		inputField.addActionListener(controller);
		inputField.addFocusListener(controller);
		model.addChangeListener(this);
		model.setPatternByString("\\d?");
	}

	
	public AbstractFieldModel getModel()
	{
		return model;
	}

	
	public Object getValue()
	{
		return model.getValue();
	}

	
	public void setModel(AbstractFieldModel model)
	{
		this.model = (NumberFieldModel) model;
		this.model.addChangeListener(this);
		inputField.setText(((String) this.model.getValue()).trim());
	}

	
	public void setValue(Object value)
	{
		model.setValue(value);
	}

	
	public void changePerformed(FieldChangeEvent event)
	{
		inputField.setText(((String) this.model.getValue()).trim());
	}

}
